package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class WebCheckFilter implements Filter {

    //路劲匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "front/**",
                "/user/login",
                "user/sendMsg",
                "/front/**"
                //"/common/**"
        };

        //1.获取拦截到的此次请求路劲 用匹配器过滤掉不需要拦截的路劲(登录 退出 及相关页面静态资源),直接放行
        String requestURI = request.getRequestURI();

        log.info("拦截到的请求路劲:{}",requestURI);
        boolean check = checkUrl(urls, requestURI);
        if(check){
            filterChain.doFilter(request,response); //放行
            return;
        }
        //2.1校验请求session内是否有用户id 有则确定已经登录过,放行(浏览器管理用户)
        if(request.getSession().getAttribute("employee") != null){
            /**
             * 通过线程的局部变量ThreadLocal存储用户id
             */
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.set(empId);

            filterChain.doFilter(request,response); //放行
            return;
        }
        //2.2校验请求session内是否有用户id 有则确定已经登录过,放行(客户端使用用户)
        if(request.getSession().getAttribute("user") != null){
            /**
             * 通过线程的局部变量ThreadLocal存储用户id
             */
            Long userId = (Long) request.getSession().getAttribute("user");
            //线程容器副本存入userId
            BaseContext.set(userId);

            filterChain.doFilter(request,response); //放行
            return;
        }
        //3.未登录,返回未登录的反馈(通过输出流的方式向前端页面响应数据)
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean checkUrl(String[] urls,String requestURI){

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            //如果返回true标识匹配上了 进行判断
            if(match){
                return true;
            }
        }
        return false;
    }


}
